<template>
    <div class="app-container">
      <pqc-info ref="pqcInfo" :form="form" ></pqc-info>
      <el-divider content-position="center" >检验信息</el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="检验单编号" prop="ipqcCode">
              <el-input v-model="form.ipqcCode" placeholder="请输入检验单编号" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="检验单名称" prop="ipqcName">
              <el-input v-model="form.ipqcName" placeholder="请输入检验单名称" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="3" align="middle">
            <el-image fit="contain" v-if="form.checkResult == 'ACCEPT'" :src="acceptImg"/>
            <el-image fit="contain" v-else-if="form.checkResult == 'REJECT'" :src="rejectImg"/>
            <el-image fit="contain" v-else :src="prepareImg"/>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="检测日期" prop="inspectDate">
              <el-date-picker clearable
                              v-model="form.inspectDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择检测日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="检测人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检测人员" readonly>
                <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测结果" prop="checkResult">
              <el-select v-model="form.checkResult" placeholder="请选择检验结果">
                <el-option
                  v-for="dict in dict.type.mes_qc_result"
                  :key="dict.value"
                  v-if="dict.value!='EXEMPT'"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="本次检测数量" prop="quantityCheck">
              <el-input v-model="form.quantityCheck" placeholder="请输入检测数量" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格品数量" prop="quantityQualified">
              <el-input-number
                :min="0"
                :max="form.quantityCheck"
                v-model="form.quantityQualified"
                @change="jiSuanBuHege()"
                placeholder="请输入合格数量"
                :disabled="ipqclineList.length>0"
              />
            </el-form-item>
          </el-col>
            <el-col :span="8">
              <el-form-item label="不合格数" prop="quantityUnqualified">
                <el-input-number
                  :min="0"
                  :max="form.quantityCheck"
                  :disabled="ipqclineList.length>0"
                  @change="jiSuanHege()"
                  v-model="form.quantityUnqualified"
                  placeholder="请输入不合格数量"
                 />
              </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="remark">
              <FileUpload
                :limit="5"
                :fileSize="100"
                :fileType="fileType"
                :value="fileList"
                :optType="optType"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <el-divider  content-position="center">检测项</el-divider>
      <el-card shadow="always"  class="box-card">
        <el-table border v-loading="loading" :data="ipqclineList">
          <el-table-column label="检测项名称" width="120px" align="center" prop="indexName" />
          <el-table-column label="检测项类型" width="100px" align="center" prop="indexType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_index_type" :value="scope.row.indexType"/>
            </template>
          </el-table-column>
          <el-table-column label="检测工具" width="100px"align="center" prop="qcTool" />
          <el-table-column label="检测要求"width="100px" align="center" prop="checkMethod" />
          <el-table-column label="标准值" width="150" align="center" prop="standerVal" >
            <template v-slot="scope">
              <span v-if="scope.row.indexType == 'QUALITATIVE'">--</span>
              <span v-else>{{scope.row.standerVal}}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" width="150"  align="center" prop="unitOfMeasure" >
            <template v-slot="scope">
              <span v-if="scope.row.indexType == 'QUALITATIVE'">--</span>
              <span v-else>{{scope.row.unitOfMeasure}}</span>
            </template>
          </el-table-column>
          <el-table-column label="误差上限" width="150"  align="center" prop="thresholdMax" >
            <template v-slot="scope">
              <span v-if="scope.row.indexType == 'QUALITATIVE'">--</span>
              <span v-else>{{scope.row.thresholdMax}}</span>
            </template>

          </el-table-column>
          <el-table-column label="误差下限"  width="150" align="center" prop="thresholdMin" >
            <template v-slot="scope">
              <span v-if="scope.row.indexType == 'QUALITATIVE'">--</span>
              <span v-else>{{scope.row.thresholdMin}}</span>
            </template>
          </el-table-column>

          <el-table-column
            v-for="(col, index)  in realValueColumns"
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            align="center"
            >
            <template v-slot="scope">
              <el-input-number v-model="scope.row.realValues[`${index}`]" @change="computeValue1(`${index}`)" size="mini" v-if="scope.row.indexType!='QUALITATIVE'"/>
              <el-switch v-model="scope.row.realValues[`${index}`]" @change="computeValue1(`${index}`)"  :active-value="1" :inactive-value="0" active-color="green" active-text="合格" v-else/>
            </template>

          </el-table-column>
        </el-table>

<!--        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />-->
      </el-card>
      <el-form label-width="100px">
        <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
            <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
            <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存</el-button>
            <el-button type="success" @click="handleFinish" v-if="form.status =='PREPARE' && optType !='view'  && form.ipqcId !=null">完成</el-button>
            <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>

    </div>
</template>
<script>
import { addIpqc, getIpqc, getIpqcInfoBySourceDocId, updateIpqc, addRrIpqc, updateRrIpqc } from "@/api/mes/qc/ipqc";
import { genCode } from "@/api/system/autocode/rule"
import WorkorderSelect from "@/components/workorderSelect/single.vue"
import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue"
import Ipqcline from "../ipqc/line.vue";
import UserSelect from "@/components/userSelect/single.vue";
import { getUserProfile } from "@/api/system/user";
import {listNoPage} from "@/api/mes/qc/ipqcline";
import {templateIndexList} from "@/api/mes/qc/templateindex"
import pqcInfo from "@/views/mes/qc/pendinginspect/pqcInfo.vue";

export default {
  name: "IpqcAdd",
  components: { WorkorderSelect, WorkstationSelect, Ipqcline, UserSelect,pqcInfo},
  dicts: ['mes_ipqc_type','mes_qc_result','mes_order_status','mes_index_type'],
  props: {
    workOrderId: null,
    workOrderCode: null,
    workOrderName: null,
    workstationId: null,
    workstationCode: null,
    workstationName: null,
    taskId: null,
    taskCode: null,
    taskName: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    quantityCheck: null
  },
  data() {
    return {
      realValueColumns:[],
      resultArray:[],
      // 总条数
      total: 0,
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipqcId: null,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: null,
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unitOfMeasure: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
      },
      // 过程检验单行表格数据
      ipqclineList: [],
      acceptImg: require('@/assets/images/accept.png'),
      rejectImg: require('@/assets/images/reject.png'),
      prepareImg: require('@/assets/images/prepare.png'),
      autoGenFlag: false,
      optType: 'add',
      // 表单参数
      form: {},
      // 上传文件类型
      fileType: ["pdf","doc", "xls","jpg","png"],
      // 上传文件列表
      fileList: [],
      // 表单校验
      rules: {
        ipqcCode: [
          { required: true, message: "请输入或生产检验单编号", trigger: "blur" }
        ],
       /* ipqcType: [
          { required: true, message: "请选择检验类型", trigger: "change" }
        ],*/
        workorderCode: [
          { required: true, message: "请选择生产工单", trigger: "blur" }
        ],
        workstationCode: [
          { required: true, message: "请选择工作站", trigger: "blur" }
        ],
        quantityCheck: [
          { required: true, message: "检测数量不能为空", trigger: "blur" }
        ],
        quantityUnqualified: [
          { required: true, message: "不合格品数量不能为空", trigger: "blur" }

        ],
        inspectDate: [
          { required: true, message: "请选择检验时间", trigger: "blur" }
        ],
        inspector: [
          { required: true, message: "请选择检验人员", trigger: "blur" }
        ],
        checkResult: [
          { required: true, message: "请选择检验结果", trigger: "change" }
        ],
      },
      // 当前登录用户
      user: null,
    }
  },
  created() {
    this.reset();
    if(this.$route.params.sourceDocId) {
      getIpqcInfoBySourceDocId(this.$route.params.sourceDocId).then(response => {
        if (response.data) {
          this.form = response.data;
          this.getLineList();
          if (!this.form.ipqcCode) {
            genCode('IPQC_CODE').then(response => {
              this.form.ipqcCode = response;
            });

          }
          this.form.quantityCheck = new Number(this.$route.params.quantityUncheck);
          this.form.status = 'PREPARE';
        } else {
          this.reset();
          this.getRealValueColumns();
          genCode('IPQC_CODE').then(response => {
            this.form.ipqcCode = response;
          });
        }
      })
    }

  },
  methods: {
    jiSuanBuHege(){
      if(this.ipqclineList==0){
        this.form.quantityUnqualified=this.form.quantityCheck-this.form.quantityQualified;
      }
    },
    jiSuanHege(){
      if(this.ipqclineList==0){
        this.form.quantityQualified=this.form.quantityCheck-this.form.quantityUnqualified;
      }
    },
    computeValue1(ipqclineList){
      this.realValueColumns.forEach((it,index)=>{
        let result=true;
        ipqclineList.forEach(item => {
          //定性
          if(item.indexType == 'QUALITATIVE'){
            if(item.realValues[index]==0){
              result=false;
              return;
            }
          }else{
            if(item.realValues[index]<item.standerVal+item.thresholdMin||item.realValues[index]>item.standerVal+item.thresholdMax){
              result=false;
              return;
            }
          }
        });
        this.resultArray[index]=result;
      })
      let heGeShu=0;
      let buHeGeShu=0;
      this.resultArray.forEach(i=> {
        if(i!=null){
          if(i) {
            heGeShu++;
          }else{
            buHeGeShu++;
          }
        }
      })
        this.form.quantityQualified=heGeShu;
        this.form.quantityUnqualified = buHeGeShu;
    },
    getTemplateIndex(){
      templateIndexList(this.form.taskId).then(response => {
        this.ipqclineList = response.rows;
        this.ipqclineList.map(item => {
          let defaultV=0;
          if(item.indexType == 'QUALITATIVE'){
            defaultV=1;
          }
          let realValues=[];
          for(let i=1;i<=this.form.quantityCheck;i++){
            realValues.push( defaultV);
          }
          this.$set(item,'realValues', realValues);
        })
        this.total = response.total;
        this.loading = false;
      });

    },
    getRealValueColumns(){
      this.setRealValueColumns1();
     this.getTemplateIndex();
    },
    setRealValueColumns1(){
      this.realValueColumns= Array.from({length: this.form.quantityCheck}, (_, index) => {
        return {
          label: '实际值'+(index+1),
          prop: 'realValue'+(index+1),
          width: 150
        }
      });
      this.resultArray=Array.from({length: this.form.quantityCheck});
    },
    setRealValueColumns2(){
      this.realValueColumns= Array.from({length: this.ipqclineList[0].realValues.length}, (_, index) => {
        return {
          label: '实际值'+(index+1),
          prop: 'realValue'+(index),
          width: 150
        }
      });
      this.resultArray=Array.from({length: this.ipqclineList[0].realValues.length});
    },
    /** 查询过程检验单行列表 */
    getLineList() {
      this.loading = true;
      listNoPage({ipqcId: this.form.ipqcId}).then(response => {
        this.ipqclineList = response.data;
        if(this.ipqclineList.length>0&&this.ipqclineList[0].realValues!=null){
          this.setRealValueColumns2();
        }else{
          this.setRealValueColumns1();
        }
        this.loading = false;
        this.$emit('onHandleReset');
      });
    },
    // 取消按钮
    cancel() {
        const obj = { path: "/mes/qc/pendinginspect" };
        this.$tab.closeOpenPage(obj);
    },
    handleReset(){
      getIpqc(this.form.ipqcId).then(response => {
        this.form.crQuantity = response.data.crQuantity;
        this.form.majQuantity = response.data.majQuantity;
        this.form.minQuantity = response.data.minQuantity;
        this.form.crRate=response.data.crRate;
        this.form.majRate=response.data.majRate;
        this.form.minRate=response.data.minRate;
        this.form.attr2 = response.data.attr2;
        response.data.attr2 === null ? this.fileList = [] : this.fileList = response.data.attr2.split(',');
      });
    },
    // 表单重置
    reset() {
      this.form = {
        ipqcId: null,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: 'PQC',
        templateId: null,
        sourceDocId: this.$route.params.sourceDocId,
        sourceDocType: this.$route.params.sourceDocType,
        sourceDocCode: this.$route.params.sourceDocCode,
        sourceLineId: this.$route.params.sourceLineId,
        workorderId: this.$route.params.workOrderId,
        workorderCode: this.$route.params.workOrderCode,
        workorderName: this.$route.params.workOrderName,
        taskId: this.$route.params.taskId,
        taskCode: this.$route.params.taskCode,
        taskName: this.$route.params.taskName,
        workstationId: this.$route.params.workstationId,
        workstationCode: this.$route.params.workstationCode,
        workstationName: this.$route.params.workstationName,
        processId: null,
        processCode: null,
        processName: null,
        itemId: this.$route.params.itemId,
        itemCode: this.$route.params.itemCode,
        itemName: this.$route.params.itemName,
        specification: this.$route.params.specification,
        unitOfMeasure: this.$route.params.unitOfMeasure,
        quantityCheck: new Number(this.$route.params.quantityUncheck),
        quantityUnqualified: null,
        quantityQualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        inspectDate: new Date(),
        inspector: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.autoGenFlag = false;
      this.resetForm("form");
      this.getUser();
      this.fileList = [];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.quantityQualified=this.form.quantityCheck-this.form.quantityUnqualified;
          this.form.ipqclineList=this.ipqclineList;
          if(this.form.sourceDocType =='返修报工'){
            if (this.form.ipqcId != null) {
              updateRrIpqc(this.form).then((response) => {
                this.$modal.msgSuccess('修改成功')
              })
            } else {
              addRrIpqc(this.form).then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.form.ipqcId = response.data //将返回的ID保存
              })
            }
          }else{
            if (this.form.ipqcId != null) {
              updateIpqc(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
              });
            } else {
              addIpqc(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.form.ipqcId = response.data; //将返回的ID保存
                this.getLineList();
              });
            }
          }
        }
      });
    },
    //点击完成
    handleFinish(){
      let that = this;
      if(this.form.checkResult == null){
        this.$modal.msgError("请选择检测结果！");
        return;
      }
      let num = parseInt(that.form.quantityCheck);
      let he = that.form.quantityQualified + that.form.quantityUnqualified
      if (num !== he) {
        this.$modal.msgError("合格品数量与不合格品数量之和不等于检测数量！")
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否完成检验单编制？【完成后将不能更改】').then(function(){
            that.form.status = 'FINISHED';
            that.submitForm();
            that.cancel();
          });
        }
      });
    },

    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj != undefined && obj != null){
        this.form.inspector = obj.nickName;
      }
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.inspector = this.user.nickName;
      });
    },
    handleUploaded(data) {
      this.form.attr2 = data;
    },
    handleRemoved(data) {
      this.form.attr2 = data;
    },

  }
}
</script>
<style lang="scss" >


</style>
